package com.kasax.hipermission;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;

import androidx.appcompat.app.AlertDialog;

import com.kasax.utils.CommonUtils;

import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;
import java.util.Map;

public class PermissionProcessor {
    private static final int MY_PERMISSION_REQUEST = 0x21;

    private final WeakReference<Activity> mActWerf;
    private RequestPermissionType requestPermissionType;
    private OnPmrmissionResultCallback mCallback;

    public void injectCallback(OnPmrmissionResultCallback callback) {
        this.mCallback = callback;
    }

    private enum RequestPermissionType {
        SDKCARD_GROUP
    }

    public PermissionProcessor(WeakReference<Activity> werf) {
        this.mActWerf = werf;
    }

    public void detach() {
        if (mActWerf != null) {
            Activity activity = mActWerf.get();
            if (activity != null) {
                activity = null;
            }
            mActWerf.clear();
        }
    }

    /**
     * 申请权限
     *
     * @param permissions
     * @return
     */
    public void requestPermission(String[] permissions) {
        if (permissions == null || permissions.length == 0) {
            return;
        }

        if (checkPermission(permissions)) {
            return;
        }
        mActWerf.get().requestPermissions(permissions, MY_PERMISSION_REQUEST);
    }

    /**
     * 检查是否有权限
     *
     * @param permissions
     * @return
     */
    public boolean checkPermission(String[] permissions) {
        boolean hasPermission = true;
        if (permissions == null || permissions.length == 0) {
            return hasPermission;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                Activity activity = mActWerf.get();
                int result = activity.checkSelfPermission(permission);
                if (result != PackageManager.PERMISSION_GRANTED) {
                    hasPermission = false;
                }
            }
        }
        return hasPermission;
    }

    public void processSdCardGroupPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            CommonUtils.goRequestAppFileAccessPermissionPage(mActWerf.get(), MY_PERMISSION_REQUEST);
            requestPermissionType = RequestPermissionType.SDKCARD_GROUP;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermission(PermissionConstants.SDCARD_PERMISSION_GROUP);
        } else {
            // 不做啥，直接处理
        }
    }

    public void onActivityPermissionResult(int requestCode) {
        if (requestCode == MY_PERMISSION_REQUEST) {
            if (requestPermissionType == RequestPermissionType.SDKCARD_GROUP) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    if (Environment.isExternalStorageManager()) {
                        if (mCallback != null) {
                            mCallback.onDone();
                        }
                    }
                }
            }
        }
    }

    public interface OnPmrmissionResultCallback {
        void onDone();
    }

    /**
     * 权限申请回调处理
     *
     * @param requestCode
     * @param permissions
     */
    public void onRequestPermissionsResult(int requestCode, String[] permissions) {
        if (requestCode != MY_PERMISSION_REQUEST) {
            return;
        }

        /**
         * 缓存的是没有权限的集合
         */
        Map<String, Boolean> permissionResult = new LinkedHashMap<>();
        if (permissions != null && permissions.length > 0) {
            for (String permission : permissions) {
                int result = mActWerf.get().checkSelfPermission(permission);
                if (result != PackageManager.PERMISSION_GRANTED) {
                    permissionResult.put(permission, false);
                }
            }

            if (!permissionResult.isEmpty()) {
                StringBuffer sb = new StringBuffer();
                for (String key : permissionResult.keySet()) {
                    sb.append(key).append(",");
                }
                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                }

                AlertDialog alertDialog = new AlertDialog.Builder(mActWerf.get()).setTitle("权限申请提醒").setMessage(
                        "您有如下权限未申请，会影响功能的使用" + sb + "，请在系统设置中为应用赋予权限, 是否需要跳转到系统设置?").setPositiveButton("确认",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 跳转到系统设置
                                dialog.dismiss();
                                CommonUtils.goAppDetailsPage(mActWerf.get());
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
                alertDialog.show();
            } else {
                if (mCallback != null) {
                    mCallback.onDone();
                }
            }
        }
    }
}
